import re
import logging
from datetime import datetime, timedelta


def handle_time(publish_time_str):
    now = datetime.now()
    if '分钟前' in publish_time_str:
        minutes_ago = int(re.findall(r'(\d+)分钟前', publish_time_str)[0])
        return now - timedelta(minutes=minutes_ago)
    elif '秒前' in publish_time_str:
        seconds_ago = int(re.findall(r'秒前', publish_time_str)[0])
        return now - timedelta(seconds=seconds_ago)
    elif '今天' in publish_time_str:
        time_part = re.findall(r'今天 (\d+:\d+)', publish_time_str)[0]
        return datetime.strptime(f"{now.year}-{now.month}-{now.day} {time_part}", '%Y-%m-%d %H:%M')
    # 新增：处理标准时间格式 + 来源（如："2022-06-04 23:54:45 来自iPhone 11"）
    elif re.match(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', publish_time_str):
        time_part = publish_time_str[:19]  # 提取 "YYYY-MM-DD HH:MM:SS"
        return datetime.strptime(time_part, '%Y-%m-%d %H:%M:%S')

    # 默认格式："X月X日 HH:mm"
    else:
        try:
            month, day, time_part = re.findall(r'(\d+)月(\d+)日 (\d+:\d+)', publish_time_str)[0]
            return datetime.strptime(f"{now.year}-{month}-{day} {time_part}", '%Y-%m-%d %H:%M')
        except Exception as e:
            logging.error(f"无法解析时间字符串: {publish_time_str}")
            return now  # 解析失败返回当前时间兜底